﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AdvancedCSharp
{
    class Program
    {
        /// <summary>
        /// Delegate is an object that knows how to call a method
        /// </summary>
        /// <param name="x"> a number</param>
        /// <returns>square of given number</returns>
        delegate int Transformer(int x);
        static int Square(int x) { return x * x; }

        static void Main(string[] args)
        {
            //simple delegate
            Transformer t = Square; // equals Transformer t = new Transformer(Square);
            int answer = t(3); // equals int answer = t.Invoke(3);
            Console.WriteLine("answer is " + answer);

            //multicast delegate
            ProgressReporter p = WriteProgressToConsole;
            p += WriteProgressToFile;
            Util.HardWork(p);

            Console.ReadLine();
        }

        #region Multicast Delegate

        public delegate void ProgressReporter(int percentComplete);

        public class Util
        {
            public static void HardWork(ProgressReporter p)
            {
                for (int i = 0; i < 10; i++)
                {
                    p(i * 10);
                    Thread.Sleep(100);
                }
            }
        }

        static void WriteProgressToConsole(int percentComplete)
        {
            Console.WriteLine(percentComplete);
        }

        static void WriteProgressToFile(int percentComplete)
        {
            File.WriteAllText("progress.txt", percentComplete.ToString());
        }

        #endregion

    }
}
